import { get } from 'lodash-es'
import React, { useState } from 'react'
import { Resizable, ResizeCallbackData, ResizeHandle  } from 'react-resizable'
import { ResizePaneModeEnums } from './model'
import Icon from '../Icon'

import 'react-resizable/css/styles.css'

interface ResizePaneProps {
  width?: number,
  height?: number,
  children?: React.ReactNode,
  mode?: ResizePaneModeEnums
}

const ResizePane: React.FC<ResizePaneProps> = (props) => {
  const {
    width = 300,
    height = 0,
    mode = ResizePaneModeEnums.Vertical,
    children,
  } = props;
  const [rw, setRW] = useState(width);
  const [rh, setRH] = useState(height);

  function onResize(__: React.SyntheticEvent, data: ResizeCallbackData) {
    const { width, height } = get(data, 'size');
    if (mode == ResizePaneModeEnums.Vertical) {
      setRW(width);
    } else if (mode == ResizePaneModeEnums.Horizontal) {
      setRH(height);
    } else {
      setRW(width);
      setRH(height);
    }
  }

  function renderHandle(__: ResizeHandle, ref: React.RefObject<any>) {
    return (
      <span ref={ref} 
      className='absolute bg-white top-1/2 right-[-4px] pt-1 pb-1 cursor-ew-resize shadow shadow-black border border-gray-100'>
        <Icon size={8} name="resize" />
      </span>
    )
  }

  return (
    <Resizable 
    width={rw}
    height={rh}
    maxConstraints={[500, 200]} 
    minConstraints={[200, 200]}
    handle={renderHandle}
    onResize={onResize}
    >
      <div className='w-full h-full' style={{ width: `${rw}px`, height: rh ? `${rh}px` : 'auto' }}>
        { children }
      </div>
    </Resizable>
  )
}

export default ResizePane
